package com.zhuss.third;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.zhuss.bean.unit.WXSession;
import com.zhuss.exception.AabException;
import com.zhuss.exception.ExceptionCode;
import com.zhuss.util.HttpUtilEx;

/**
 * @Author: zhushanshuo
 * @Date: 2020/04/03 19:54
 */
@Component
public class WXThirdService {
	
	@Value("${wx.appId}")
    private String appId;
    
	@Value("${wx.appSecret}")
    private String appSecret;

    public String JSCODE_LOGIN_URL;
    
    
    public WXSession query(String jscode) throws AabException {
    	
    	JSCODE_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+appSecret+"&js_code={JSCODE}&grant_type=authorization_code";
    	
        if(StringUtils.isBlank(jscode)) {
        	throw new AabException(ExceptionCode.登录凭证code无效);
        }
        String url = JSCODE_LOGIN_URL.replace("{JSCODE}", jscode);
        String res = HttpUtilEx.doGet(url);
//        log.info("wx session result:{}",res);
        if(StringUtils.isBlank(res)) {
        	throw new AabException(ExceptionCode.微信授权接口服务通信失败);
        }
        JSONObject json = JSONObject.parseObject(res);
        if (json.containsKey("errcode")) {
            throw new AabException(String.valueOf(json.get("errmsg")), ExceptionCode.服务异常.getCode());
        } else {
            return new WXSession(String.valueOf(json.get("openid")), String.valueOf(json.get("session_key")));
        }
    }
    
}
